# -*- coding: utf-8 -*-
import wsgiref.handlers
import sys
import os
import string
import codecs
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging
import urlparse
from dateutil import parser

DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
LIB_PATH = os.path.join(DIR_PATH, "lib")
EXTRA_PATHS = []
for path in os.listdir(LIB_PATH):
    fullpath = os.path.join(LIB_PATH, path)
    if os.path.isdir(fullpath) and not path.startswith("."):
        EXTRA_PATHS.append(fullpath)
sys.path = sys.path + EXTRA_PATHS

from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import urlfetch
from datetime import datetime, timedelta
from django.core import serializers
from django.http import HttpResponsePermanentRedirect
from django.utils import simplejson as json
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.api import images 
from google.appengine.ext.db import GqlQuery
from models import *
from utilities import *

webapp.template.register_template_library('customfilters')
webapp.template.register_template_library('smart_if')


# Set to true if we want to have our webapp print stack traces, etc
_DEBUG = True


class BaseRequestHandler(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the variables present in this function.
  """
  def generate(self, template_name, template_values={}):
    values = {
      'request': self.request,
      'application_name': 'Fieltro',
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('admin', template_name))
    os.environ['DJANGO_SETTINGS_MODULE'] = 'conf.settings'
    self.response.out.write(template.render(path, values, debug=_DEBUG))

    
class Index(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
    template_values = {

    }
    self.generate('index.html', template_values)


class Teams(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = Team.all()
    queryitems.order('-pubDate')
    teams = queryitems.fetch(500)

    template_values = {
      'teams': teams,
    }
    self.generate('teams.html', template_values)

class TeamAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if action == 'delete':
      item = Team.get(itemkey)
      item.delete()
      self.redirect("/admin/teams", False)
      return 1

    elif action=='edit':
      try:
        item = Team.get(itemkey)
      except:
        queryitem = Team.all()
        queryitem.filter(' key = ', int(itemkey))
        items = queryitem.fetch(1)
        item = items[0]

      queryitems = Country.all()
      queryitems.order('name')
      countries = queryitems.fetch(500)

      template_values = {
        'countries': countries,
        'team': item,
        'key': itemkey,
      }

    elif action=='new':
      queryitems = Country.all()
      queryitems.order('name')
      countries = queryitems.fetch(500)

      template_values = {
        'countries': countries,
      }

    self.generate("team.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = Team.get(itemkey)
      creating = False
    else:
      item = Team()
      creating = True

    if self.request.get("save")!='':
      if creating:
        # Get the latest orderNum used, increase it by 1 and use it
        queryitem = Team.all()
        queryitem.order('-teamId')
        items = queryitem.fetch(1)

        if not len(items) > 0:
          lastId = 0
        else:
          lastId = items[0].teamId
          
        teamId = lastId + 1
        item.teamId = teamId
      
      item.name = self.request.get("name")
      item.slug = self.request.get("slug")
      item.country = self.request.get("country")
      item.confederation = self.request.get("confederation")
      item.genrenumber = self.request.get("genrenumber")
      item.stadium = self.request.get("stadium")
      item.city = self.request.get("city")
      if self.request.get("theStadium") != "":
        item.theStadium = True
      else:
        item.theStadium = False
      item.put()
      
    self.redirect("/admin/teams", True)

class Countries(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = Country.all()
    queryitems.order('name')
    countries = queryitems.fetch(500)

    template_values = {
      'countries': countries,
    }
    self.generate('countries.html', template_values)

class CountryAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if action == 'delete':
      item = Country.get(itemkey)
      item.delete()
      self.redirect("/admin/countries", False)
      return 1

    elif action=='edit':
      try:
        item = Country.get(itemkey)
      except:
        queryitem = Team.all()
        queryitem.filter(' key = ', int(itemkey))
        items = queryitem.fetch(1)
        item = items[0]

      name = item.name
      slug = item.slug
      code = item.code
      confederation = item.confederation
      

      template_values = {
        'name': name,
        'slug': slug,
        'code': code,
        'confederation': confederation,
        'key': itemkey,
      }

    elif action=='new':
      template_values = {
      }

    self.generate("country.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = Country.get(itemkey)
      creating = False
    else:
      item = Country()
      creating = True

    if self.request.get("save")!='':
      if creating:
        # Get the latest orderNum used, increase it by 1 and use it
        queryitem = Country.all()
        queryitem.order('-countryId')
        items = queryitem.fetch(1)

        if not len(items) > 0:
          lastId = 0
        else:
          lastId = items[0].countryId

        countryId = lastId + 1
        item.countryId = countryId

      item.name = self.request.get("name")
      item.slug = self.request.get("slug")
      item.code = self.request.get("code")
      item.confederation = self.request.get("confederation")
      item.put()

    self.redirect("/admin/countries//new/", True)

class Matchs(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = Match.all()
    queryitems.order('-pubDate')
    matchs = queryitems.fetch(500)

    template_values = {
      'matchs': matchs,
    }
    self.generate('matchs.html', template_values)

class MatchAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = Team.all()
    queryitems.order('name')
    teams = queryitems.fetch(500)
    
    if action == 'delete':
      item = Match.get(itemkey)
      item.delete()
      self.redirect("/admin/matchs", False)
      return 1

    elif action=='edit':
      try:
        item = Match.get(itemkey)
      except:
        queryitem = Match.all()
        queryitem.filter(' key = ', int(itemkey))
        items = queryitem.fetch(1)
        item = items[0]
      
      stadium = item.stadium
      
      queryteams = Team.all()
      queryteams.filter(' stadium = ', stadium)
      stadiumTeams = queryteams.fetch(1)
      if len(stadiumTeams) > 0:
        stadiumTeam = stadiumTeams[0]
      
        template_values = {
          'teams': teams,
          'match': item,
          'stadiumTeam': stadiumTeam,
          'stadium': stadium,
          'key': itemkey,
        }
      else:
        template_values = {
          'teams': teams,
          'match': item,
          'stadium': stadium,
          'key': itemkey,
        }

    elif action=='new':

      template_values = {
        'teams': teams,
      }

    self.generate("match.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = Match.get(itemkey)
      creating = False
    else:
      item = Match()
      creating = True

    if self.request.get("save")!='':
      if creating:
        # Get the latest orderNum used, increase it by 1 and use it
        queryitem = Match.all()
        queryitem.order('-matchId')
        items = queryitem.fetch(1)

        if not len(items) > 0:
          lastId = 0
        else:
          lastId = items[0].matchId
          
        matchId = lastId + 1
        item.matchId = matchId
      
      item.homeTeam = self.request.get("homeTeam")
      item.awayTeam = self.request.get("awayTeam")
      item.teams = self.request.POST.getall("team")
      item.matchDate = parser.parse(self.request.get("matchDate"))
      item.competition = self.request.get("competition")
      item.season = self.request.get("season")
      item.phase = self.request.get("phase")
      teamStadium = self.request.get("stadium")
      queryteams = Team.all()
      queryteams.filter(' name = ', teamStadium)
      teams = queryteams.fetch(1)
      team = teams[0]
      item.stadium = team.stadium
      item.put()
      
    self.redirect("/admin/matchs//new/", True)

class CropImage(webapp.RequestHandler):
  def get(self, category):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    photobig=self.request.get("photobig")
    
    template_values = {
      'photobig' : photobig,
      'category' : category
    }
    path = os.path.join(os.path.dirname(__file__), 'admin/gallery-crop.html')
    self.response.out.write(template.render(path, template_values))

class SaveImage(webapp.RequestHandler):
  def post(self, item):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    photobig = self.request.get("photobig")
    posy = int(self.request.get("posy"))
    posx = int(self.request.get("posx"))

    #try:
    result = urlfetch.fetch(photobig)
    #except:
      #self.response.out.write("Image too big!")
      #return 0

    content = result.content
    img = images.Image(content)

    originalwidth = float(img.width)
    originalheight = float(img.height)
    
    ratio = float(originalwidth/originalheight)

    resizedheight = float(480)
    resizedwidth = float(320)

    calculatedwidth = math.ceil(float(float(originalwidth * resizedheight) / originalheight))
    calculatedheight = math.ceil(float(float(originalheight * resizedwidth) / originalwidth))
    
    if ratio > 0.66666667:
      resizedcontent = images.resize(content, int(calculatedwidth), int(resizedheight))
      
      left_x = float(posx / calculatedwidth)
      right_x = float((posx + 320) / calculatedwidth)

      top_y = float(posy / resizedheight)
      bottom_y = float(posy + 480 / resizedheight)

      #self.response.out.write("ratio > 4/6 - " + str(left_x) + ", " + str(top_y) + ", " + str(right_x) + ", " + str(bottom_y))
      #return 0

    else:
      resizedcontent = images.resize(content, int(resizedwidth), int(calculatedheight))

      left_x = float(posx / resizedwidth)
      right_x = float((posx + 320) / resizedwidth)

      top_y = float(posy / calculatedheight)
      bottom_y = float((posy + 480) / calculatedheight)
      
      #self.response.out.write("ratio < 4/6 - " + str(left_x) + ", " + str(top_y) + ", " + str(right_x) + ", " + str(bottom_y))
      #return 0

    #posx: 0, posy: 5
    #left_x: 0.0, top_y: 0.0104166666667, right_x: 1.01587301587, bottom_y: 1.01041666667

    croppedcontent = images.crop(resizedcontent, left_x, top_y, right_x, bottom_y)
    img = images.Image(croppedcontent)

    myfile = File()
    myfile.bytes_content = db.Blob(croppedcontent)
    myfile.height = img.height
    myfile.width = img.width

    queryitem = File.all()
    queryitem.order('-fileId')
    items = queryitem.fetch(1)

    if not len(items) > 0:
      lastId = 0
    else:
      lastId = items[0].fileId

    fileId = lastId + 1
    myfile.fileId = fileId
    
    if item == "man":
      myfile.category = "man"
    if item == "woman":
      myfile.category = "woman"
    if item == "funny":
      myfile.category = "funny"
    if item == "odd":
      myfile.category = "odd"
    myfile.put()

    #self.response.out.write(str(left_x) + ", " + str(top_y) + ", " + str(right_x) + ", " + str(bottom_y))
    self.response.out.write("/image/" + str(fileId) + "/")



class Users(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
    template_values = {

    }
    self.generate('users.html', template_values)


class UploadImage(BaseRequestHandler):
  def get(self, filekey, callback):
    imagetype = self.request.get('imagetype')
    template_values = {
      'filekey': filekey,
      'callback': callback,
      'imagetype': imagetype
    }
    self.generate('fileupload.html', template_values)

  def post(self, filekey, callback):

    for upload in self.request.POST.getall('fileupload[]'):

      #item = self.request.POST.get('fileupload')
      imagetype = self.request.get('imagetype')

      file_content = upload.file.read()
      content = db.Blob(file_content)

      myfile = File()
      img = images.Image(content)
      myfile.bytes_content = content
      myfile.height = img.height
      myfile.width = img.width
      myfile.imagetype = imagetype
      myfile.put()

      template_values = {
        'fileKey': str(myfile.key()),
        'posted': True,
        'callback': callback,
        'imagetype': imagetype
      }
    self.generate('fileupload.html', template_values)


class DeleteImage(BaseRequestHandler):
  def post(self, key):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    myfile = File.get(key)
    myfile.delete()


# Create first admin user to start working with the app.
class PopulateUsers(BaseRequestHandler):
  def get(self):
    user = CustomUser(name="Admin",
              user=users.GetCurrentUser(),
              role="admin")
    user.put()


def main():
  application = webapp.WSGIApplication([
    ('/admin/populateusers/', PopulateUsers),
    ('/admin/populateusers', PopulateUsers),
    ('/admin/upload/(.*)/(.*)/', UploadImage),
    ('/admin/image/delete/(.*)/', DeleteImage),
    ('/admin/teams', Teams),
    ('/admin/teams/(.*)/(new)/', TeamAction),
    ('/admin/teams/(.*)/(save)/', TeamAction),
    ('/admin/teams/(.*)/(delete)/', TeamAction),
    ('/admin/teams/(.*)/(edit)/', TeamAction),
    ('/admin/countries', Countries),
    ('/admin/countries/(.*)/(new)/', CountryAction),
    ('/admin/countries/(.*)/(save)/', CountryAction),
    ('/admin/countries/(.*)/(delete)/', CountryAction),
    ('/admin/countries/(.*)/(edit)/', CountryAction),
    ('/admin/matchs', Matchs),
    ('/admin/matchs/(.*)/(new)/', MatchAction),
    ('/admin/matchs/(.*)/(save)/', MatchAction),
    ('/admin/matchs/(.*)/(delete)/', MatchAction),
    ('/admin/matchs/(.*)/(edit)/', MatchAction),
    ('/admin/', Index),
  ], debug=_DEBUG)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == "__main__":
  main()
